package com.htgd.gardenexpo.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.htgd.gardenexpo.dao.*;
import com.htgd.gardenexpo.entity.CommonResult;
import com.htgd.gardenexpo.entity.GeConUserCompete;
import com.htgd.gardenexpo.entity.WxUser;
import com.htgd.gardenexpo.page.MySportsQuery;
import com.htgd.gardenexpo.page.RecommendQuery;
import com.htgd.gardenexpo.service.CommonService;
import com.htgd.gardenexpo.service.DeviceService;
import com.htgd.gardenexpo.service.GeBaseDictService;
import com.htgd.gardenexpo.service.WxUserService;
import com.htgd.gardenexpo.utils.DateUtils;
import com.htgd.gardenexpo.utils.HttpRequest;
import com.htgd.gardenexpo.vo.FindItemVO;
import com.htgd.gardenexpo.vo.RecommendVO;
import org.apache.poi.ss.formula.functions.T;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author: 王秀田
 * @date: 2024/11/11 15:58
 * @description: TODO
 */
@Service
public class CommonServiceImpl implements CommonService {

    @Autowired
    private GeConCalendarDao geConCalendarDao;

    @Autowired
    private GeConCompetitionSportsMapper geConCompetitionSportsMapper;

    @Autowired
    private GeConLeisureSportsMapper geConLeisureSportsMapper;

    @Autowired
    private GeBaseDictService geBaseDictService;

    @Autowired
    private GeConUserCompeteMapper geConUserCompeteMapper;

    @Autowired
    private WxUserService wxUserService;

    @Autowired
    private GeConFoodShopMapper geConFoodShopMapper;

    @Value("${device.item_ids}")
    private String itemIds;

    @Value("${device.tenant_id}")
    private String tenantId;

    @Value("${device.race_list_url}")
    private String raceListUrl;

    @Value("${local.url}")
    public String local_url;

    @Autowired
    private DeviceService deviceService;

    @Autowired
    private GeConPlantMapper geConPlantMapper;

    @Autowired
    private GeConSocialContentMapper geConSocialContentMapper;

    @Autowired
    private GeConFunSportsMapper geConFunSportsMapper;

    /**
     * 查询 热点推荐（热点，景观地标，智慧运动，展馆展览）
     * @param recommendQuery
     * @return
     */
    @Override
    public List<RecommendVO> getRecommendList(RecommendQuery recommendQuery) {
        return geConCalendarDao.getRecommendList(recommendQuery);
    }

    /**
     * 查询 景观地标
     * @param recommendQuery
     * @return
     */
    @Override
    public List<RecommendVO> getSceneList(RecommendQuery recommendQuery) {
        return geConCalendarDao.getSceneList(recommendQuery);
    }

    @Override
    public List<RecommendVO> getSceneListById(List<Integer> ids) {
        return geConCalendarDao.getSceneListById(ids);
    }

    /**
     * 查询 智慧运动
     * @param recommendQuery
     * @return
     */
    @Override
    public List<RecommendVO> getCalendarList(RecommendQuery recommendQuery) {
        return geConCalendarDao.getCalendarList(recommendQuery);
    }

    /**
     * 查询 展馆展览
     * @param recommendQuery
     * @return
     */
    @Override
    public List<RecommendVO> getVenueList(RecommendQuery recommendQuery) {
        return geConCalendarDao.getVenueList(recommendQuery);
    }

    /**
     * 统计 热点推荐（热点，景观地标，智慧运动，展馆展览）
     * @param recommendQuery
     * @return
     */
    @Override
    public int getRecommendCount(RecommendQuery recommendQuery) {
        return geConCalendarDao.getRecommendCount(recommendQuery);
    }

    /**
     * 统计 景观地标
     * @param recommendQuery
     * @return
     */
    @Override
    public int getSceneCount(RecommendQuery recommendQuery) {
        return geConCalendarDao.getSceneCount(recommendQuery);
    }

    /**
     * 统计 智慧运动
     * @param recommendQuery
     * @return
     */
    @Override
    public int getCalendarCount(RecommendQuery recommendQuery) {
        return geConCalendarDao.getCalendarCount(recommendQuery);
    }

    /**
     * 统计 展馆展览
     * @param recommendQuery
     * @rn
     */
    @Override
    public int getVenueCount(RecommendQuery recommendQuery) {
        return geConCalendarDao.getVenueCount(recommendQuery);
    }

    /**
     * 查询智慧运动
     * @param recommendQuery
     * @return
     */
    @Override
    public CommonResult getSmartSportsList(RecommendQuery recommendQuery) {
        List<HashMap> list = new ArrayList<>();

        if(Objects.equals(recommendQuery.getType(),"1")){//赛事
            PageHelper.startPage(recommendQuery.getPageNum(), recommendQuery.getPageSize());
            list = geConCompetitionSportsMapper.getSmartSportsList(recommendQuery);
            Iterator<HashMap> iterator = list.iterator();
            while (iterator.hasNext()) {
                HashMap map = iterator.next();
                //人数
                Long num = geConUserCompeteMapper.selectCount(new LambdaQueryWrapper<GeConUserCompete>()
                        .eq(GeConUserCompete::getSportsType,"1")
                        .eq(GeConUserCompete::getMotionId,map.get("id").toString())
                        .eq(GeConUserCompete::getStatus,"1"));
                map.put("num",num);
                //时间格式化
                Iterator<Map.Entry> entries = map.entrySet().iterator();
                while (entries.hasNext()) {
                    Map.Entry entry = entries.next();
                    System.out.println(entry.getKey() + ":" + entry.getValue());
                    if(Objects.equals(entry.getKey(),"startTime")){
                        entry.setValue(entry.getValue().toString().replace("T"," ").substring(0,19));
                    }
                    if(Objects.equals(entry.getKey(),"endTime")){
                        entry.setValue(entry.getValue().toString().replace("T"," ").substring(0,19));
                    }
                    if(Objects.equals(entry.getKey(),"startDate")){
                        entry.setValue(entry.getValue().toString().replace("T"," ").substring(0,19));
                    }
                    if(Objects.equals(entry.getKey(),"endDate")){
                        entry.setValue(entry.getValue().toString().replace("T"," ").substring(0,19));
                    }
                }
                //当前状态
                DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
                LocalDateTime startDate = LocalDateTime.parse(map.get("startDate").toString(), df);
                LocalDateTime endDate = LocalDateTime.parse(map.get("endDate").toString(), df);
                LocalDateTime startTime = LocalDateTime.parse(map.get("startTime").toString(), df);
                LocalDateTime endTime = LocalDateTime.parse(map.get("endTime").toString(), df);
                LocalDateTime now = LocalDateTime.now();
                //当前状态
                if (now.isAfter(startDate) && now.isBefore(endDate)) {
                    map.put("activeText","报名中");
                    map.put("active","3");
                } else if (now.isAfter(startTime) && now.isBefore(endTime)) {
                    map.put("activeText","进行中");
                    map.put("active","1");
                }else if(now.isAfter(endTime)){
                    map.put("activeText","已结束");
                    map.put("active","2");
                }else {
                    map.put("activeText","未开始");
                    map.put("active","0");
                }
            }
        }else{//挑战
            PageHelper.startPage(recommendQuery.getPageNum(), recommendQuery.getPageSize());
            list = geConLeisureSportsMapper.getLeisureSportsList(recommendQuery);
            Iterator<HashMap> iterator = list.iterator();
            while (iterator.hasNext()) {
                HashMap map = iterator.next();
                Long num = geConUserCompeteMapper.selectCount(new LambdaQueryWrapper<GeConUserCompete>()
                        .eq(GeConUserCompete::getSportsType,"2")
                        .eq(GeConUserCompete::getMotionId,map.get("id").toString())
                        .eq(GeConUserCompete::getStatus,"1"));
                map.put("num",num);
                //时间格式化
                Iterator<Map.Entry> entries = map.entrySet().iterator();
                while (entries.hasNext()) {
                    Map.Entry entry = entries.next();
                    System.out.println(entry.getKey() + ":" + entry.getValue());
                    if(Objects.equals(entry.getKey(),"startTime")){
                        entry.setValue(entry.getValue().toString().replace("T"," ").substring(0,19));
                    }
                    if(Objects.equals(entry.getKey(),"endTime")){
                        entry.setValue(entry.getValue().toString().replace("T"," ").substring(0,19));
                    }
                    if(Objects.equals(entry.getKey(),"startDate")){
                        entry.setValue(entry.getValue().toString().replace("T"," ").substring(0,19));
                    }
                    if(Objects.equals(entry.getKey(),"endDate")){
                        entry.setValue(entry.getValue().toString().replace("T"," ").substring(0,19));
                    }
                }
                //当前状态
                DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
                LocalDateTime startDate = LocalDateTime.parse(map.get("startDate").toString(), df);
                LocalDateTime endDate = LocalDateTime.parse(map.get("endDate").toString(), df);
                LocalDateTime startTime = LocalDateTime.parse(map.get("startTime").toString(), df);
                LocalDateTime endTime = LocalDateTime.parse(map.get("endTime").toString(), df);
                LocalDateTime now = LocalDateTime.now();
                //当前状态
                if (now.isAfter(startDate) && now.isBefore(endDate)) {
                    map.put("activeText","报名中");
                    map.put("active","3");
                } else if (now.isAfter(startTime) && now.isBefore(endTime)) {
                    map.put("activeText","进行中");
                    map.put("active","1");
                }else if(now.isAfter(endTime)){
                    map.put("activeText","已结束");
                    map.put("active","2");
                }else {
                    map.put("activeText","未开始");
                    map.put("active","0");
                }
            }
        }
        return CommonResult.success(String.valueOf(list.size()),list);
    }

    @Override
    public Long getSmartSportsCount(RecommendQuery recommendQuery) {
        Long count = 0L;
        if(Objects.equals(recommendQuery.getType(),"1")){
            count = geConCompetitionSportsMapper.getSmartSportsCount(recommendQuery);
        }else if(Objects.equals(recommendQuery.getType(),"2")){
            count = geConLeisureSportsMapper.getLeisureSportsCount(recommendQuery);
        }else{
            count = geConCompetitionSportsMapper.getPopularSportsCount(recommendQuery);
        }
        return count;
    }

    /**
     * 查询用户赛事数据
     * @return
     */
    @Override
    public void getUserSportData(String raceId, String userId) {
        GeConUserCompete geConUserCompete1 = geConUserCompeteMapper.selectOne(new LambdaQueryWrapper<GeConUserCompete>()
            .eq(GeConUserCompete::getMotionId,raceId)
            .eq(GeConUserCompete::getUserId,Long.valueOf(userId))
            .ne(GeConUserCompete::getScoreStatus,2).last("limit 1"));
        if(Objects.isNull(geConUserCompete1)){
            Map<String,Object> payloadMap  = new HashMap<>();
            payloadMap.put("itemId",itemIds);
            payloadMap.put("raceId",raceId);
            payloadMap.put("userId",Long.valueOf(userId));
            Map<String,Object> headers = new HashMap<>();
            headers.put("Content-Type", "application/json");
            headers.put("Tenant-Id", tenantId);
            String result = null;
            try {
                headers.put("Authorization", "Bearer " + deviceService.deviceLogin());
                result = HttpRequest.sendHttpPostRequest(raceListUrl,
                        new HashMap<>(), headers, JSON.toJSONString(payloadMap));
            }catch (Exception e) {
                e.printStackTrace();
            }
            if(result!=null&&result!=""){
                JSONObject jsonObject = (JSONObject) JSONObject.parse(result);
                Boolean ok = (Boolean) jsonObject.get("ok");
                Integer code = (Integer) jsonObject.get("code");
                if(ok && code==0){
                    String data = (String) jsonObject.get("data");
                    JSONArray jsonArray = JSON.parseArray(data);
                    for (int i = 0; i < jsonArray.size(); i++) {
                        String element = jsonArray.getString(i);
                        JSONObject jsonObject1 = JSONObject.parseObject(element);
                        String sumMileage = (String) jsonObject1.get("sumMileage");
                        String sumDuration = (String) jsonObject1.get("sumDuration");
                        Integer isFinish = (Integer) jsonObject1.get("isFinish");
                        GeConUserCompete geConUserCompete = new GeConUserCompete();
                        if(Objects.equals(geConUserCompete1.getSportsType(),"2")){
                            if(Objects.equals(isFinish,0)){
                                geConUserCompete.setScoreStatus(2);
                            }
                            if(Objects.equals(isFinish,1)){
                                geConUserCompete.setScoreStatus(3);
                            }
                        }
                        if(Objects.equals(geConUserCompete1.getSportsType(),"1")){
                            geConUserCompete.setScoreStatus(geConUserCompete1.getScoreStatus());
                        }
                        geConUserCompete.setUserId(Long.valueOf(userId));
                        geConUserCompete.setMotionId(raceId);
                        geConUserCompete.setSumDuration(Long.valueOf(sumDuration));
                        geConUserCompete.setSumMileage(Double.valueOf(sumMileage));
                        geConUserCompeteMapper.updateUserCompete(geConUserCompete);
                    }
                }
            }
        }
    }

    @Override
    public PageInfo<HashMap> mySportsList(MySportsQuery mySportsQuery, String openId) {
        mySportsQuery.setOpenId(openId);
        PageHelper.startPage(mySportsQuery.getPageNum(), mySportsQuery.getPageSize());
        List<HashMap> list = geConUserCompeteMapper.mySportsList(mySportsQuery);
        Iterator<HashMap> iterator = list.iterator();
        while (iterator.hasNext()) {
            HashMap map = iterator.next();
            map.put("activeText",geBaseDictService.getTextByCodeAndValue("status_competition", map.get("active").toString()));

            Iterator<Map.Entry> entries = map.entrySet().iterator();
            while (entries.hasNext()) {
                Map.Entry entry = entries.next();
                if(Objects.equals(entry.getKey(),"startTime")){
                    entry.setValue(entry.getValue().toString().replace("T"," ").substring(0,19));
                }
                if(Objects.equals(entry.getKey(),"createTime")){
                    entry.setValue(entry.getValue().toString().replace("T"," ").substring(0,19));
                }
                if(Objects.equals(entry.getKey(),"endTime")){
                    entry.setValue(entry.getValue().toString().replace("T"," ").substring(0,19));
                }
                if(Objects.equals(entry.getKey(),"startDate")){
                    entry.setValue(entry.getValue().toString().replace("T"," ").substring(0,19));
                }
                if(Objects.equals(entry.getKey(),"endDate")){
                    entry.setValue(entry.getValue().toString().replace("T"," ").substring(0,19));
                }
            }
        }
        return new PageInfo<>(list);
    }

    @Override
    public CommonResult find() {
        Map<String,Object> map = new HashMap<>();

        //趣运动
        List<FindItemVO> sportsList = geConFunSportsMapper.getFindList();
        map.put("sportsList",sportsList);


        //美食店铺
        List<FindItemVO> foodShopList = geConFoodShopMapper.getFindList();
        map.put("foodShopList",foodShopList);

        //植物
        List<FindItemVO> plantList = geConPlantMapper.getFindList();
        map.put("plantList",plantList);

        //乐分享
        List<FindItemVO> socialList = geConSocialContentMapper.getFindList();
        map.put("socialList",socialList);

        return CommonResult.success("查询成功",map);
    }
}
